//
//  JKNetworkingTool.swift
//  JKWeibo
//
//  Created by albert on 16/5/14.
//  Copyright © 2016年 albert. All rights reserved.
//  网络工具类

import UIKit
import AFNetworking

class JKNetworkingTool: AFHTTPSessionManager {

    // Swift推荐我们这样写单例，当然使用dispatch也可以
    static let sharedInstance: JKNetworkingTool = {
        
        // 注意：baseUrl后面一定要写上斜线 /
        let baseUrl = NSURL(string: "https://api.weibo.com/")
        let instance = JKNetworkingTool(baseURL: baseUrl, sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
        
        // AFN默认是不支持解析text/plain的，需要自己添加
        instance.responseSerializer.acceptableContentTypes = NSSet(objects: "text/plain", "application/json", "text/json", "text/javascript") as Set
        
        return instance
    }()
    
    //MARK: - 外部控制方法
    /** 获取首页数据 */
    func loadStatuses(since_id : String, max_id: String, finished: (array: [[String: AnyObject]]?, error: NSError?) -> ()){
        // 异步执行的结果一般通过回调返回
        
        assert(JKUserAccount.loadUserAccount()?.access_token != nil, "必须授权之后才能获取微博数据")
        
        // 1.准备请求URL路径
        let urlStr = "2/statuses/home_timeline.json"
        
        // 2.准备参数
        let temp = (max_id != "0") ? "\(Int(max_id)! - 1)" : max_id
        let parameters = ["access_token" : JKUserAccount.loadUserAccount()!.access_token!, "since_id" : since_id, "max_id": temp]
        
        // 3.发送请求
        GET(urlStr, parameters: parameters, success: { (task, objc) -> Void in
            
            // 4.返回数据给调用者的回调
            guard let arr = (objc as! [String: AnyObject])["statuses"] as? [[String: AnyObject]] else {
                finished(array: nil, error: NSError(domain: "jkdev123cool", code: 1000, userInfo: ["message" : "没有获取到数据"]))
                return
            }
            
            finished(array: arr, error: nil)
            
            }) { (task, error) -> Void in
                finished(array: nil, error: error)
        }
    }
    
    /** 发布微博 */
    func sendStatus(status: String, pic: UIImage?, finished: (dict: [String : AnyObject]?, error: NSError?) -> ()) {
        
        // 准备URL路径
        var urlStr = "2/statuses/"
        
        // 准备参数
        let params = ["access_token" : JKUserAccount.loadUserAccount()!.access_token!, "status" : status]
        
        // 如果图片为空，就是文字微博
        if pic == nil {
            // 1.拼接URL路径
            urlStr += "update.json"
            
            // 2.发送POST请求
            POST(urlStr, parameters: params, success: { (task, objc) -> Void in
                finished(dict: objc as? [String : AnyObject], error: nil)
                
                }) { (task, error) -> Void in
                    finished(dict: nil, error: error)
            }
        }else { // 图片不为空，图片微博
            // 1.拼接URL路径
            urlStr += "upload.json"
            
            // 2.发送POST请求
            POST(urlStr, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
                
                // 将图片转为NSData
                let imageData = UIImagePNGRepresentation(pic!)!
                
                // 拼接图片内容
                formData.appendPartWithFileData(imageData, name: "pic", fileName: "123.png", mimeType: "image/png")
                
                }, success: { (task, objc) -> Void in
                    finished(dict: objc as? [String : AnyObject], error: nil)
                    
                }, failure: { (task, error) -> Void in
                    finished(dict: nil, error: error)
            })
        }
    }
}
